package com.mxpio.erp.technology.service.impl;

import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mxpio.erp.common.technology.entity.VBomInfo;
import com.mxpio.erp.common.technology.service.VBomInfoService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;

@Service
public class VBomInfoServiceImpl implements VBomInfoService {

	@Override
	@Transactional(readOnly = true)
	public Map<String, List<VBomInfo>> list(Criteria c) {
		List<VBomInfo> bomInfos =JpaUtil.linq(VBomInfo.class).where(c).list();
		
		return JpaUtil.classify(bomInfos, "itemCode");
	}

	@Transactional(readOnly = true)
	@Override
	public List<Map<String,Object>> findCircularReferenceBom(){
		String sqlIn = "select distinct parent_code_ itemCode from v_mb_erp_technology_bom t where t.parent_code_ in (select item_code_ from v_mb_erp_technology_bom)";
		List<String> resultList = JpaUtil.nativeQuery(sqlIn).getResultList();//中间组件
		List<Map<String,Object>> errorBoms = new ArrayList<>();
		Map<String, List<VBomInfo>> bomSources = this.list(Criteria.create());
		for(String per :resultList){
			this.factorial(per,bomSources);
			if (getSum()>=51){
				int count = (getPath().length()-getPath().replace(per, "").length())/per.length();//统计itemcode在path出现的次数
				if(count>1){
					Map<String,Object> returnMap = new HashMap<>();
					returnMap.put("itemCode", per);
					returnMap.put("circulateTime",getSum());
					returnMap.put("path",getPath());
					errorBoms.add(returnMap);
				}
			}
		}
		return errorBoms;
	}
	private int sum = 0;

	private String path = "";

	//将sum值返回给调用者。
	public int getSum() {
		return sum;
	}
	public String getPath(){
		return path;
	}
	public void factorial(String itemCode, Map<String, List<VBomInfo>> bomSources) {
		// 将递归次数清零,若要统计所有的，则将count注释即可
		sum = 0;
		path = itemCode+"=>";
		this.getResult(itemCode,bomSources);
	}

	public void getResult(String itemCode,Map<String, List<VBomInfo>> bomSources) {
		List<VBomInfo> boms = bomSources.get(itemCode);
		if(boms == null){
			boms = Collections.emptyList();
			path +="||";
		}
		for(VBomInfo bom : boms){
			String parentCode = bom.getParentCode();
			String itemCode1 = bom.getItemCode();
			if(StringUtils.isBlank(parentCode)) {
				continue;
			}
			if(StringUtils.isBlank(itemCode1)) {
				continue;
			}
			sum += 1;
			path +=parentCode+"=>";
			if (sum>51){
				return ;
			}
			getResult(parentCode,bomSources);
		}
	}
}
